<script setup lang="ts">
import type { UploadFile, UploadInstance, UploadRequestOptions } from 'element-plus'
import { ElMessage } from 'element-plus'

const emit = defineEmits<{
  (e: 'importExcel', data: FormData): void
}>()

const acceptTypes = '.xls, .xlsx'

const dialogVisible = ref(false)

const fileList = ref<UploadFile[]>([])

// 打开弹窗
function openDialog() {
  dialogVisible.value = true
}

// 上传前校验
function beforeUpload(file: File) {
  const isExcel = ['.xls', '.xlsx', '.XLS', '.XLSX'].some(ext => file.name.endsWith(ext))
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return true
}

const importRef = ref<UploadInstance>()

function importHandler() {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件！')
    return
  }
  importRef.value!.submit()
}

async function handleImport(options: UploadRequestOptions) {
  const formData = new FormData()
  formData.append('file', options.file)
  emit('importExcel', formData)
}

function importSuccess() {
  dialogVisible.value = false
  importRef.value!.clearFiles()
}

function refreshImport() {
  dialogVisible.value = false
  importRef.value!.clearFiles()
}

defineExpose({ openDialog })
</script>

<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="导入"
      width="30%"
      @close="refreshImport"
    >
      <el-upload
        ref="importRef"
        v-model:file-list="fileList"
        class="upload-demo"
        :http-request="handleImport"
        :limit="1"
        :accept="acceptTypes"
        :before-upload="beforeUpload"
        :auto-upload="false"
        :on-success="importSuccess"
      >
        <template #trigger>
          <el-button type="primary">
            选择文件
          </el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            仅支持 {{ acceptTypes }} 格式文件，且不超过10MB
          </div>
        </template>
      </el-upload>

      <template #footer>
        <span class="dialog-footer">
          <el-button class="ml-3" type="success" @click="importHandler">
            上传
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped></style>
